/**
 * @author huangjacky
 * @date 2014-10-14
 * @version 1.0
 * @email huangjacky@163.com
 * @description
 */
'use strict';
(function ($) {
    $.fn.extend({
        lazyloading: function (opt) {
            var defaults = {
                delay: 0
            };
            var self = this;
            var options = $.extend(defaults, opt);
            var getWindowInfo = function () {
                if ("pageYOffset" in window) {
                    return {
                        x: window.pageXOffset,
                        y: window.pageYOffset,
                        w: window.innerWidth,
                        h: window.innerHeight
                    }
                } else {
                    var el = document.documentElement;
                    return {
                        x: el.scrollLeft,
                        y: el.scrollTop,
                        w: el.clientWidth,
                        h: el.clientHeight
                    }
                }

            };
            var check = function () {
                var t = getWindowInfo();
                self.each(function (idx) {
                    var $this = $(this);
                    var left = 0;
                    var top = 0;
                    var el = this;
                    while (el && el.offsetParent) {
                        left += el.offsetLeft;
                        top += el.offsetTop;
                        el = el.offsetParent;
                    }
                    if (
                        left > t.x && left < t.x + t.w &&
                        top > t.y && top < t.y + t.h
                        ) {//开始正式加载
                        var href = $this.data("href");
                        if ($this.is("img")) {
                            if($this.attr("src") == href)
                                return;
                            if (options.delay > 0) {
                                setTimeout(function () {
                                    $this.attr("src", href);
                                }, options.delay);
                            } else {
                                $this.attr("src", href);
                            }
                        } else if ($this.is("div")) {
                            if (options.delay > 0) {
                                setTimeout(function () {
                                    $this.load(href);
                                }, options.delay);
                            } else {
                                $this.load(href);
                            }
                        }
                    }
                });
            };
            $(window).on("scroll", function (evt) {
                check();
            });
            check();
        }
    });
})(jQuery);